package com.white.loglib;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by ytf on 2020/7/24 024.
 * Description:
 */
public class LogMessagerService extends Service
{

    private ClientServer server;

    @Override
    public void onCreate()
    {
        super.onCreate();
        server = new ClientServer("127.0.0.1", 3000);
        server.start();
    }

    public boolean isConnected(){
        return server.isActive();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if(server != null)
        {
            server.closeClient();
        }
    }

    public void sendMessage(int level, String msg)
    {
        if(server != null)
        {
            server.sendMsg(level, msg);
        }
    }

    private class ClientServer extends Thread
    {

        private int port;
        private String ip;

        private ArrayBlockingQueue<LogProtocolBean> queue = new ArrayBlockingQueue<>(20);

        public ClientServer(String ip, int port){
            super();
            this.ip = ip;
            this.port = port;
        }

        private Socket client;
        private AtomicBoolean alive = new AtomicBoolean(false);

        @Override
        public void run()
        {
            try
            {
                client = new Socket(ip, port);
                alive.set(true);
                Log.e("s", "本地打印服务已启动");
//                new Thread(new ReadTask()).start();
                new Thread(new WriteTask()).start();
            }catch (Exception e)
            {
                stopSelf();
            }
        }

        public void closeClient()
        {
            try
            {
                queue.put(new LogProtocolBean(-1, null));
                alive.set(false);
                if(client != null){
                    client.close();
                    client.shutdownInput();
                    client.shutdownOutput();
                    client = null;
                }
            }catch (Exception e)
            {

            }
        }

        private boolean isActive()
        {
            return client != null
                    && !client.isClosed()
                    && client.isConnected()
                    && alive.get();
        }

        public void sendMsg(int level, String msg)
        {
            if(isActive())
            {
                try
                {
                    queue.put(new LogProtocolBean(level, msg));
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }

        private class ReadTask implements Runnable
        {

            @Override
            public void run()
            {
                byte[] buf = new byte[1024];

                while (isActive())
                {
                    try
                    {
                        if(client != null){
                            InputStream inputStream = client.getInputStream();
                            if(inputStream != null)
                            {
                                int size = inputStream.read(buf);
                                String msg = new String(buf, 0, size);
                            }
                        }
                    }catch (Exception e)
                    {

                    }
                }
            }
        }

        private class WriteTask implements Runnable
        {

            @Override
            public void run()
            {
                while(isActive())
                {
                    try
                    {
                        LogProtocolBean content = queue.take();
                        if(!content.isEOF())
                        {
                            OutputStream outputStream = client.getOutputStream();
                            if(outputStream != null)
                            {
                                outputStream.write(content.getBytes());
                                outputStream.flush();
                            }
                        }
                    }catch (Exception e)
                    {
                       Log.e("s", "写入异常");
                    }
                }
            }
        }
    }

    private MyBinder binder = new MyBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        return binder;
    }

    public class MyBinder extends Binder
    {
        public LogMessagerService getService()
        {
            return LogMessagerService.this;
        }
    }
}
